package ru.alexo.whiskey;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Represents a midi file
 * 
 * @author Exaybachay
 */
public class Midi {

    public static final short DEFAULT_TPQ = 480;

    private static final String MIDI_HEADER = "MThd";

    private final List<MidiTrack> tracks = new ArrayList<MidiTrack>();

    public Midi() {
    }

    /**
     * Creates a new track and adds it to the Midi stream.
     * 
     * @return the created track.
     */
    public MidiTrack createTrack() {
	MidiTrack track = new MidiTrack();
	tracks.add(track);

	return track;
    }

    /**
     * Serializes the midi content into {@link ByteArrayOutputStream}.
     * 
     * @return midi output stream.
     * @throws IOException
     */
    public void serializeMidiContent(OutputStream outputStream) throws IOException {
	DataOutputStream data = new DataOutputStream(outputStream);

	data.writeBytes(MIDI_HEADER);
	data.writeInt(0x06);
	data.writeInt(0x01);
	data.writeShort(DEFAULT_TPQ);
	data.flush();

	for (MidiTrack track : tracks) {
	    outputStream.write(track.getTrackBytes());
	}
    }

}
